<template>
  <view class="page">
    <!-- 导航栏 -->
    <tui-navigation-bar title="首页" inTabBar></tui-navigation-bar>

    <section class="header primary-box">
      <view class="top">
        <view class="top-logo-box">
          <image :src="$format(loginInfo, 'loginimg')" mode="aspectFill" class="top-logo"></image>
        </view>
        <view class="top-content">
          <view class="top-content-left">
            <view class="title" @click="$open('/switch-business/switch-business')">{{ businessName }}</view>

            <view class="mt-2 fs-xxs">
              {{ $format(loginInfo, 'banme', '') }}
            </view>
          </view>
          <view
            v-if="$format(loginInfo, 'version_type') === versionTypeTextDict['共享版']"
            class="top-content-right"
            @tap="$open('/switch-business/switch-business')"
            hover-class="hover-jump"
          >
            <view>切换商家</view>
            <tui-icon name="arrowright" size="20"></tui-icon>
          </view>
        </view>
      </view>

      <view class="bottom">
        <view class="address">{{ $format(loginInfo, 'address', '暂未获取到门店地址') }}</view>
        <view class="is-flex-col flex-center" hover-class="hover-jump" @click="openLocation($format(loginInfo, 'address'))">
          <my-icon name="solid-location" :color="$variables.gold" hoverClass></my-icon>
          <view class="fs-xxs mt-2">导航</view>
        </view>
        <view class="is-flex-col flex-center" hover-class="hover-jump" @click="callPhone()">
          <my-icon name="phone" :color="$variables.gold" hoverClass></my-icon>
          <view class="fs-xxs mt-2">电话</view>
        </view>
      </view>
    </section>

    <!-- 广告位 -->
    <section class="introduce-container">
      <swiper
        v-if="!$isEmpty(introduceList)"
        class="introduce-swiper"
        :indicator-dots="false"
        :autoplay="true"
        :interval="5000"
        :duration="150"
        :circular="true"
        indicator-color="#C8CEE1"
        indicator-active-color="#EDD2B2"
      >
        <swiper-item v-for="(introduce, index) in introduceList" :key="introduce.pop_title" class="introduce-swiper-item" @click="previewImg(introduceList, index)">
          <view class="introduce-img-box">
            <image v-if="introduce.pop_img" :src="introduce.pop_img" class="introduce-img" mode="aspectFill"></image>
          </view>
        </swiper-item>
      </swiper>
    </section>

    <!-- 充值套餐 -->
    <section class="recharge">
      <view class="link-content" @click="$open('/recharge/recharge')">
        <view class="link-title">充值套餐</view>
        <view class="link-right arrow-right" hover-class="hover-jump">更多</view>
      </view>

      <view v-if="rechargeCardList && rechargeCardList.length > 0" class="recharge-content">
        <swiper
          class="recharge-card-swiper"
          :indicator-dots="true"
          :autoplay="false"
          :interval="5000"
          :duration="150"
          :circular="true"
          indicator-color="#C8CEE1"
          indicator-active-color="#EDD2B2"
        >
          <swiper-item v-for="(rechargeCardGroup, index) in finalRechargeCardList" :key="index" class="recharge-card-swiper-item">
            <block v-for="rechargeCard in rechargeCardGroup" :key="rechargeCard.id">
              <view @tap="handleRecharge(rechargeCard)" class="recharge-item primary-box" hover-class="hover-jump">
                <span v-if="$format(rechargeCard, 'cardtype') !== 4">充{{ rechargeCard.money }}元</span>
                <span class="text-align-center">{{ rechargeCard.title }} </span>
              </view>
            </block>
          </swiper-item>
        </swiper>
      </view>
      <view v-else class="pl-15 pr-15 mb-20 primary-grey-text fs-sm">暂无更多充值套餐数据</view>
    </section>

    <!-- 推荐套餐 -->
    <section class="recommend">
      <view class="link-content">
        <view class="link-title">推荐套餐</view>
      </view>
      <view v-if="tjMealList && tjMealList.length > 0" class="content">
        <view v-for="tjMeal in tjMealList" :key="tjMeal.goodsid" class="recommend-item primary-box" @click="toMealDetail(tjMeal)" hover-class="hover-jump">
          <view class="item-img-content">
            <image :src="tjMeal.img || '/static/images/default.jpg'" class="item-img" mode="aspectFill"></image>
          </view>
          <view class="item-content">
            <view v-if="tjMeal.tags" class="tag-list">
              <view v-for="(tjTag, index) in tjMeal.tags" :key="index" class="tag">{{ tjTag }}</view>
            </view>
            <view class="item-title">{{ tjMeal.name }}</view>
            <view v-if="tjMeal.Price" class="fs-base text-price primary-title font-weight-bold">{{ tjMeal.Price }}</view>
          </view>
        </view>
      </view>
      <view v-else class="content mb-20 primary-grey-text fs-sm">暂无更多推荐套餐数据</view>
    </section>

    <!-- loading -->
    <my-loading ref="loading"></my-loading>

    <!-- 选择房台号组件 -->
    <modal-scan ref="scanModal"></modal-scan>

    <!-- 自定义充值组件 -->
    <modal-recharge ref="rechargeModal"></modal-recharge>

    <!-- 授权手机号组件 -->
    <modal-get-user-phone ref="getUserPhoneModal"></modal-get-user-phone>

    <!-- <footer>
      <view>温之莎有限公司提供技术支持</view>
      <view> 客服电话：0755-8008</view>
    </footer> -->

    <my-tabbar></my-tabbar>
  </view>
</template>

<script>
import recharge from '@/pages/recharge/mixins/recharge'
export default {
  mixins: [recharge],
  data() {
    return {
      $variables: this.$variables,
      // 广告
      adv: null,
      // 充值套餐列表
      rechargeCardList: null,
      // 首页推荐套餐列表
      tjMealList: null,
      // 广告位图
      introduceList: null,
      // 用于区分版本
      versionTypeTextDict: { 共享版: 1, 独立版: 2 }
    }
  },
  computed: {
    // 充值套餐列表
    finalRechargeCardList() {
      return this.viewGetRchargeCardList(this.rechargeCardList, 2)
    },
    // 商家名称
    businessName() {
      const format = this.$format
      return format(this.selectBusiness, 'pt_name') || format(this.selectBusiness, 'name') || format(this.loginInfo, 'pt_name') || ''
    },
    loginInfo() {
      return this.$store.getters.loginInfo
    },
    // 选中的商家
    selectBusiness() {
      return this.$store.getters.selectBusiness
    }
  },
  onLoad(param) {
    this.analyseOnLoadParam(param)

    // 监听所有切换商家的操作，进行更新当前页面处理
    this.$eventHub.$on('selectBusiness', data => {
      console.log('selectBusiness', data)
      this.handleInit()
    })
  },
  onShow() {
    uni.hideTabBar()
  },
  onPullDownRefresh() {
    this.$refs.loading.open()
    this.handleInit()
    setTimeout(() => {
      uni.stopPullDownRefresh()
      this.$refs.loading.close()
    }, 300)
  },
  methods: {
    handleInit() {
      this.initLoginInfo().then(res => {
        // this.getBottomNav()
        this.checkExamime()
        this.getIntroduce()
        this.finalGetRechargeCardList()
        this.getTjMeal()
      })
    },
    /**
     * 解析 onLoad 参数
     * 应用场景 ： 适用于微信外部扫码进入，判断是否需要更新选中商家 、 跳转页面等操作
     */
    analyseOnLoadParam(param) {
      const onLoadParam = this.$encode(param, 'q', 'String')
      const paramObj = this.$utils.paramConvertObj(onLoadParam)
      const sortcode = this.$format(paramObj, 'sortcode')

      console.log('onLoadParam', onLoadParam, paramObj, sortcode)

      if (!sortcode) {
        this.handleInit()
        return
      }

      this.login(sortcode).then(res => {
        this.openLoginPage(res)
        this.handleInit()
      })
    },
    /**
     * 是否屏蔽扫码点单
     * 应用场景 ： 审核控制扫码点单按钮是否显示
     */
    checkExamime() {
      const baseParam = this.getBase(['token'])
      return new Promise((resolve, reject) => {
        if (!baseParam) return reject()
        console.param('是否屏蔽扫码点单', baseParam)
        this.$api
          .checkExamime(baseParam)
          .then(res => {
            console.res('是否屏蔽扫码点单', res)
            const ifScan = this.$format(res, 'data.showcheck', true)
            this.$store.dispatch('Business/setIfScan', ifScan)
            resolve(res)
          })
          .catch(err => {
            console.err('是否屏蔽扫码点单', err)
            reject(err)
          })
      })
    },
    // 用于打开后台返回的路径
    openLoginPage(param) {
      let pages = this.$format(param, 'pages')

      if (pages) {
        const tabBar = this.$store.state.TabBar.tabBar

        const ifTabBarPage = tabBar.some(item => {
          // 如果 url 不是以 / 开头，手动拼接 。 否则无法完成跳转
          if (pages.indexOf('/') !== 0) {
            pages = '/' + pages
          }

          return pages.indexOf(item.pagePath) > -1
        })

        console.log('pages >> ' + pages, 'ifTabBarPage >> ' + ifTabBarPage)

        if (ifTabBarPage) {
          uni.switchTab({ url: pages })
        } else {
          uni.redirectTo({ url: pages })
        }
      }
    },
    // 返回用于试图渲染的格式
    viewGetRchargeCardList(arr, length, diy = { title: '自定义充值' }) {
      if (!arr || arr.length === 0) return []
      const result = arr.reduce((pre, item) => {
        if (pre.length === 0) {
          pre.push([item])
          return pre
        }

        const curr = pre[pre.length - 1]
        if (curr.length !== length) {
          curr.push(item)
          return pre
        }

        const arr = []
        arr.push(item)
        pre.push(arr)
        return pre
      }, [])

      return result
    },
    callPhone() {
      const tel = this.$format(this.selectBusiness, 'tel')
      if (!tel) return this.$msg('text', '电话号码为空')
      uni.makePhoneCall({ phoneNumber: tel })
    },
    previewImg(imageList, index) {
      if (!imageList) return
      if (!imageList.length > 0) return

      const imgArr = imageList.map(item => {
        return item.pop_img
      })

      uni.previewImage({
        current: imgArr[index],
        loop: true,
        urls: imgArr
      })
    },
    toMealDetail(item) {
      this.$open('/meal-detail/meal-detail', 'nt', { data: item })
    },

    /**
     * 查询推荐套餐列表
     * 场景：首页
     */
    getTjMeal() {
      const baseParam = this.getBase(['token', 'selectuniacid', 'usertoken'])
      if (!baseParam) return
      console.param('查询推荐套餐列表', baseParam)
      this.$api
        .getTjMeal(baseParam)
        .then(res => {
          console.res('推荐套餐列表', res)
          this.tjMealList = this.$format(res, 'data')
        })
        .catch(err => {
          console.err('推荐套餐列表', err)
          this.errMsg(err, '获取推荐套餐失败')
        })
    },

    // 充值套餐
    recharge(item) {
      if (!item) return this.$refs.rechargeModal.open()
      this.$open('/recharge/recharge-details', 'nt', { data: item })
    },
    // 获取广告位图片
    getIntroduce() {
      const baseParam = this.getBase(['token', 'selectuniacid'])
      if (!baseParam) return
      this.$api
        .getIntroduce(baseParam)
        .then(res => {
          console.res('获取广告位图', res)
          this.introduceList = this.$format(res, 'data')
        })
        .catch(err => {
          console.err('获取广告位图', err)
          this.errMsg(err, '获取广告位图失败')
        })
    },
    // 获取地址经纬度
    openLocation(address) {
      if (!address) return this.$msg('text', '暂未获取到地理位置信息')
      const baseParam = this.getBase(['token', 'selectuniacid'])
      if (!baseParam) return
      Object.assign(baseParam, { address })
      console.param('获取地址经纬度', baseParam)
      this.$api
        .getAddress(baseParam)
        .then(res => {
          console.res('获取地址经纬度', res)
          const latitude = this.$format(res, 'data.latitude')
          const longitude = this.$format(res, 'data.longitude')

          if (!latitude || !longitude) return this.$msg('text', '暂未获取到地理位置信息')

          uni.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: address,
            fail: err => {
              return this.$msg('text', '打开地图失败请重试')
            }
          })
        })
        .catch(err => {
          this.errMsg(err, '暂未获取到地理位置信息')
        })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$borderX: 15px;

section {
  margin-bottom: 20px;
}

.header {
  display: flex;
  flex-flow: column nowrap;
  margin: $borderX $borderX 20px $borderX;
  font-size: $font-size-xs;
  color: $color-primary-grey-text;
  .top {
    padding: 5px 8px;
    @include is-flex(row, space-between, center, nowrap);

    .top-logo-box {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      display: block;
      margin-right: 12px;
      background: $imgBg;
      overflow: hidden;
      .top-logo {
        width: 100%;
        height: 100%;
      }
    }
    .top-content {
      flex: 1;
      @include is-flex(row, space-between, center, nowrap);
      &-left {
        @include is-flex(column, center, flex-start, nowrap);
        .title {
          color: $color-primary-title;
          font-size: $font-size-lg;
        }
      }
      &-right {
        @include is-flex(row, center, center, nowrap);
      }
    }
  }
  .bottom {
    @include is-flex(row, space-between, center, nowrap);
    border-top: 1px solid $borderColor;
    padding: 10px 5px 5px 5px;
    margin-top: 10px;
    .address {
      width: 70%;
    }
  }
}

// 广告位
.introduce-swiper {
  width: 100%;
  height: 140px;

  // height: 170px;
  .introduce-swiper-item {
    width: 100%;
    height: 100%;
    border-radius: 5px;
    overflow: hidden;
    .introduce-img-box {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 0 $borderX;
      // height: 140px;

      .introduce-img {
        width: 100%;
        height: 100%;
        @include default-img;
      }
    }
  }
}

// 首页/会员充值 - 充值套餐
.recharge {
  margin-bottom: 10px;
  .link-content {
    padding: 0 $borderX;
  }

  .recharge-card-swiper {
    width: 100%;
    height: 130px;
    .recharge-card-swiper-item {
      width: 100%;
      display: grid;
      grid-gap: 10px;
      grid-template-columns: 1fr 1fr;
      box-sizing: border-box;
      padding: 0 $borderX;
      .recharge-item {
        @include bg-red;
        @include is-flex(column, center, center, nowrap);
        border-radius: 7px;
        padding: 15px;
        height: 95px;
        overflow: hidden;
        & > span:nth-child(1) {
          color: $color-primary-text;
          font-weight: bold;
        }
        & > span:nth-child(2) {
          margin-top: 5px;
          color: $color-primary-grey-text;
          font-size: $font-size-xxs;
        }
      }
    }
  }
}

// 首页 - 推荐套餐
.recommend {
  .link-content {
    padding: 0 $borderX;
  }

  .content {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr;
    padding: 0 $borderX;
    .recommend-item {
      font-size: $font-size-xxs;
      margin-bottom: 15px;
      padding: 0;
      @include is-flex(column, stretch, flex-start, nowrap);
      .item-img-content {
        width: 100%;
        height: 160px;
        margin-bottom: 10px;
        .item-img {
          width: 100%;
          height: 100%;
          border-radius: 5px 5px 0 0;
        }
      }
      .item-content {
        width: 100%;
        padding: 0px 7px 10px 7px;
        .tag-list {
          @include is-flex(row, flex-start, center, wrap);
          .tag {
            color: $gold;
            border: 1px solid $gold;
            margin: 0 5px 5px 0;
            padding: 2px;
            border-radius: 2px;
            font-size: $font-size-xxs;
          }
        }
        .item-title {
          font-size: $font-size-base;
          padding: 3px 0 5px 0;
        }
      }
    }
  }
}

footer {
  color: $color-primary-bg-text;
  font-size: $font-size-xs;
  text-align: center;
  padding-bottom: 50px;
  @include is-flex(column, center, center, nowrap);
  @include safe-bottom-area(height);
}
</style>
